﻿using DevelopAssistant.Core.Tabs;
using DevelopAssistant.Service;
using ICSharpCode.WinFormsUI.Controls.NTimeLine;
using ICSharpCode.WinFormsUI.Docking;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace DevelopAssistant.Core.ToolBar
{
    public partial class TodoBar : DockContent
    {
        MainForm mainForm = null;

        TodoManager.ITodoService service = new TodoManager.TodoServiceImpl();

        private TodoBar()
        {
            InitializeComponent();
            InitializeControls();           
        }

        public TodoBar(MainForm form) : this()
        {
            this.mainForm = form;
        }

        public void DataBind()
        {
            try
            {
                this.TimelineControl1.StartShowLoading();

                System.Threading.Tasks.Task.Run(() => {

                    int limit = AppSettings.TodoLimit, total = 0;
                    var list = service.QueryTodoMonthList(limit, out total);

                    List<MonthItem> MonthList = new List<MonthItem>();
                    foreach (TodoManager.TodoDTO Dto in list)
                    {
                        string MonthName = Dto.YearMonth;
                        MonthItem monthItem = new MonthItem();
                        monthItem.Name = MonthName;
                        monthItem.Date = Convert.ToDateTime(Dto.YearMonth + "-01");
                        monthItem.DateLabel = TimelineControl1.ToDateLabel(monthItem.Date);

                        List<DateItem> DateList = new List<DateItem>();

                        var sublist = service.QueryTodoDateList(limit, Dto.YearMonth);

                        foreach (TodoManager.TodoDTO DateDto in sublist)
                        {
                            string DateName = Convert.ToDateTime(DateDto.DateTime).ToString("yyyy-MM-dd");
                            DateItem DateItem = new DateItem();
                            DateItem.Date = DateDto.DateTime.Value;

                            List<DateTimeItem> DateTimeList = new List<DateTimeItem>();

                            var subsublist = service.QueryTodoDateTimeList(limit, Dto.YearMonth, DateDto.DateTime.Value.ToString("yyyy-MM-dd"));

                            foreach (TodoManager.TodoDTO DateTimeDto in subsublist)
                            {
                                DateTimeItem DateTimeItem = new DateTimeItem();

                                DateTimeItem.Id = DateTimeDto.ID.ToString();
                                DateTimeItem.Name = DateTimeDto.Name;
                                DateTimeItem.Title = DateTimeDto.Name;
                                DateTimeItem.ToolTip = DateTimeDto.Title;
                                DateTimeItem.Timeliness = (Timeliness)Enum.Parse(typeof(Timeliness), DateTimeDto.Timeliness.ToString());
                                DateTimeItem.Summary = DateTimeDto.Summary;
                                DateTimeItem.DateTime = Convert.ToDateTime(DateTimeDto.DateTime);
                                DateTimeItem.ResponsiblePerson = DateTimeDto.ResponsiblePerson;
                                DateTimeItem.PersonName = GetShowPersonName(DateTimeDto.ResponsiblePerson);

                                DateTimeList.Add(DateTimeItem);
                            }

                            DateItem.List = DateTimeList;

                            DateList.Add(DateItem);
                        }

                        monthItem.List = DateList;

                        MonthList.Add(monthItem);
                    }

                    mainForm.MonthList = MonthList;

                    int totalRecords = limit < total ? limit : total;

                    if (!this.IsDisposed)
                    {
                        this.Invoke(new MethodInvoker(delegate ()
                        {
                            this.TimelineControl1.EndShowLoading();
                            this.TimelineControl1.DataList = MonthList;
                            this.TimelineControl1.DataBind();
                            this.lblRecords.Text = ("共 " + totalRecords + " / " + total + " 项").ToString();
                        }));
                    }

                });
            }
            catch (Exception ex)
            {
                DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "错误", DateTime.Now, ex.Source, ex.StackTrace);
            }

        }

        public void InitializeControls()
        {
            this.TimelineControl1.Click += TimelineControl_Click;
        }

        private string GetShowPersonName(string ResponsiblePerson)
        {
            string result = "";
            if (AppSettings.TodoShowName && !string.IsNullOrEmpty(ResponsiblePerson))
            {
                result = ResponsiblePerson.Substring(ResponsiblePerson.Length - 1);
            }
            return result;
        }

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            this.panel1.Invalidate();
        }

        private void btn_todolist_refresh_Click(object sender, EventArgs e)
        {
            DataBind();
        }

        private void TodoBar_Load(object sender, EventArgs e)
        {            
            this.TimelineControl1.DataList = mainForm.MonthList;
            this.TimelineControl1.DataBind();
            this.lblRecords.Text = ("共 " + mainForm.todoLimitRecords + " / " + mainForm.todoTotalRecords + " 项").ToString();
        }

        private void TimelineControl_Click(object sender, TimeLineEventArgs e)
        {
            if (string.IsNullOrEmpty(e.Command))
                return;

            if (e.Command.Equals("new"))
            {
                var dialogResult = new DevelopAssistant.Core.ToolBox.AddTodoForm(mainForm, e.Data).ShowDialog(this);
                if (dialogResult.Equals(DialogResult.OK))
                    DataBind();
            }
            if (e.Command.Equals("edit"))
            {
                TodoManager.TodoDTO todoItem = service.GetTodoItem(e.Data.Id);
                DateTimeItem item = new DateTimeItem();
                item.Id = todoItem.ID.ToString();
                item.Name = todoItem.Name;
                item.Title = todoItem.Title;
                item.Summary = todoItem.Summary;
                item.ResponsiblePerson = todoItem.ResponsiblePerson;
                item.DateTime = todoItem.DateTime.Value;

                Timeliness timeliness = Timeliness.Green;
                //Enum.TryParse(todoItem.Timeliness.Value.ToString(), out timeliness);
                switch (todoItem.Timeliness.Value)
                {
                    case 1:
                        timeliness = Timeliness.Green;
                        break;
                    case 5:
                        timeliness = Timeliness.Dark;
                        break;
                    case 6:
                        timeliness = Timeliness.Black;
                        break;
                }

                item.Timeliness = timeliness;
                item.Description = todoItem.Description;

                var dialogResult = new DevelopAssistant.Core.ToolBox.EditTotoForm(mainForm, item).ShowDialog(this);
                if (dialogResult.Equals(DialogResult.OK))
                    DataBind();
            }
            if (e.Command.Equals("delete"))
            {
                var dialogResult = new DevelopAssistant.Core.ToolBox.MessageDialog(DevelopAssistant.Core.Properties.Resources.warning_32px,
                    "确定要删除该数据吗？", MessageBoxButtons.OKCancel).ShowDialog(this);
                if (dialogResult.Equals(DialogResult.OK))
                {
                    service.DeleteTodoItem(e.Data.Id);
                    DataBind();
                }
            }
        }

        private void lblRecords_Click(object sender, EventArgs e)
        {
            mainForm.AddSingleContent(new TodoListManagerTab(mainForm), "待办事项管理");
        }

        public void SetTheme(string themeName)
        {
            switch (themeName)
            {
                case "Default":
                    lblRecords.ForeColor = Color.Blue;
                    label1.ForeColor = SystemColors.ControlText;
                    HeadPanel.BackColor = SystemColors.Control;
                    break;
                case "Black":
                    lblRecords.ForeColor = Color.FromArgb(083, 153, 205);
                    label1.ForeColor = Color.FromArgb(240, 240, 240);
                    HeadPanel.BackColor = Color.FromArgb(045, 045, 048);
                    break;
            }
            this.TimelineControl1.SetTheme(themeName);
        }

    }
}
